#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>

void SetNoBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);    //获取fd文件描述符的状态标记 fl是一个位图，每一个代表不同的文件描述符状态标记
    if (fl < 0)
    {
        perror("fcntl");
        return;
    }

    //将fd的文件标记fl设置回fd中，同时加上非阻塞
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);

    //for test
    std::cout << "set no block success" << std::endl;
}

int main()
{

    SetNoBlock(0);

    printf("Please Enter# ");
    fflush(stdout);

    for (;;)
    {

        char buffer[1024];
        ssize_t n = read(0, buffer, sizeof(buffer));
        if (n < 0)
        {
            if (errno == EWOULDBLOCK)
            {
                std::cout<<"0 fd data not ready,try again!"<<std::endl;

                //do other thing
                sleep(1);

                continue;
            }
            else
            {
                std::cout << "read error"
                          << ", n = " << n << ", error num: " << errno << ", error thing: " << strerror(errno) << std::endl;

                continue;
            }
        }
        else if (n == 0)
        {
            std::cout << "read done" << std::endl;
            break;
        }
        else
        {
            buffer[n - 1] = '\0'; // n-1去掉最后的回车
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}